package com.its.utils;


import com.aliyun.oss.OSS;

import com.aliyun.oss.model.*;
import com.its.config.OssConfig;
import com.its.goods.mapper.GoodsMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;

import java.io.InputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Date;

@Slf4j
@Component
public class FileUploadUtils {

    @Autowired
    private OssConfig ossConfig;
    @Autowired
    private OSS ossClient;


    // 上传文件
    public String uploadFile(String filePath, InputStream in) {
        try {
            ossClient.putObject(ossConfig.getBucketName(), filePath, in);
            // String url = "https://" + ossConfig.getBucketName() + "." + ossConfig.getEndpoint() + "/" + objectName;

            return getPreviewUrl(filePath);
        } catch (Exception e) {
            throw new RuntimeException("OSS文件上传失败", e);
        }
    }

    // 删除文件（支持完整URL或object key）
    public void deleteFile(String filePath) {
        try {
            ossClient.deleteObject(ossConfig.getBucketName(), filePath);
        } catch (Exception e) {
            throw new RuntimeException("OSS文件删除失败", e);
        }
    }

    public void download(String filePath, HttpServletResponse response) {
        try {
            OSSObject ossObject = ossClient.getObject(ossConfig.getBucketName(), filePath);
            InputStream inputStream = ossObject.getObjectContent();
            response.reset();
            response.setContentType("application/octet-stream");
            String filename = new File(filePath).getName();
            response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));
            ServletOutputStream outputStream = response.getOutputStream();
            byte[] b = new byte[1024];
            int len;
            // 从输入流中读取一定数量的字节，并将其存储在缓冲区字节数组中，读到末尾返回-1
            while ((len = inputStream.read(b)) > 0) {
                outputStream.write(b, 0, len);
            }
            inputStream.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public String getPreviewUrl(String objectName) {
        /*try {
            // 设置1小时有效期
            Date expiration = new Date(System.currentTimeMillis() + 30 * 24 * 3600 * 1000);
            URL url = ossClient.generatePresignedUrl(ossConfig.getBucketName(), objectName, expiration);
            return url.toString();
        } catch (Exception e) {
            throw new RuntimeException("获取预览链接失败", e);
        }*/
        try {
            // 使用公开 URL，不需要过期时间
            String publicUrl = "https://" + ossConfig.getBucketName() + "." + ossConfig.getEndpoint() + "/" + objectName;
            return publicUrl;
        } catch (Exception e) {
            throw new RuntimeException("获取预览链接失败", e);
        }
    }
}
